import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import Login from '@/views/login/index.vue'
import Layout from '@/views/layout/index.vue'
import Search from '@/views/search/index.vue'
import MyOrder from '@/views/myorder/index.vue'
import Pay from '@/views/pay/index.vue'
import ProDetail from '@/views/prodetail/index.vue'
import SearchList from '@/views/search/list.vue'
import Home from '@/views/layout/home.vue'
import Category from '@/views/layout/category.vue'
import User from '@/views/layout/user.vue'
import Cart from '@/views/layout/cart.vue'
import store from '../store/index'
import Totalcomment from '@/views/prodetail/totalcomment.vue'
import Address from '@/views/address/index.vue'
import Edit from '@/views/edit/index.vue'


export const routes = [

  {
    path: '/',
    redirect: '/home',
    name: 'LayoutIndex',
    component: Layout,
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/category',
        component: Category,
      },
      {
        path: '/user',
        component: User
      },
      {
        path: '/cart',
        component: Cart
      }

    ]
  },
  {
    // 独立单独展示的都是一级路由
    path: '/login',
    component: Login,

  },

  {
    path: '/search',
    component: Search,
  },
  {
    path: '/myorder',
    component: MyOrder
  },
  {
    path: '/pay',
    component: Pay
  },
  {
    path: '/prodetail/:id',
    component: ProDetail
  },
  {
    path: '/searchlist',
    component: SearchList
  },
  {
    path: '/totalcomment/:id',
    component: Totalcomment,
  },
  {
    path: '/address',
    component: Address,
  },
  {
    path: '/edit/:item',
    component: Edit,

  }





]
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes
})

// 所有的路由在真正被访问到之前（解析渲染对应组件页面前），都会先经过全局前置守卫，只有他放行，我们才能到相应的页面


// 全局前置导航守卫

// to：到哪里去，到哪去的完整路由信息对象（路径，参数）

// from：从哪里来，从哪来的完整路由信息对象（路径，参数）

// next（）：是否放行

// （1）next（） 直接放行，放行到to要去的路径
// （2）next（路径）  进行拦截，拦截到next里面配置的路径


// 需要授权才能访问的页面
const authUrls = ['/pay', '/myorder']


router.beforeEach((to, from, next) => {
  if (!authUrls.includes(to.path)) {
    // 非权限页面直接放行,不用做任何操作
    next()
    return
  }

  const storeToken = store.getters.storeToken
  if (storeToken) {
    next()
  } else {
    next('/login')
  }

  // if (to.path === '/address' && from.path === '/pay')

  // console.log(from, to, next);

})


export default router
